/**
 * 
 */
package edu.cmu.cs.webapp.ioms.views;

import java.util.Map;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.UIJob;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.OrderDAOImpl;
import edu.cmu.cs.webapp.ioms.logging.Alerts;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.ui.providers.order.OrdersTableViewerContentProvider;
import edu.cmu.cs.webapp.ioms.ui.providers.order.OrdersTableViewerLabelProvider;
import edu.cmu.cs.webapp.ioms.utils.IOMSUtils;
import edu.cmu.cs.webapp.ioms.utils.SWTUtils;

/**
 * @author Christian
 * 
 */
public class OrdersListView extends ViewPart implements ISelectionProvider {

	public static final String ID_VIEW = "edu.cmu.cs.webapp.ioms.views.orderslist";

	private TableViewer viewer;
	private OrderFilter viewerFilter;

	private Table table;
	private Combo searchChoice;
	private Text searchText;
	ITableLabelProvider labelProvider;

	private PurchaseOrder[] orders;

	private Map<String, Object> searchCriteria;

	/**
	 * 
	 */
	public OrdersListView() {
		viewerFilter = new OrderFilter();
		labelProvider = new OrdersTableViewerLabelProvider();
	}

	@Override
	public void init(IViewSite site) throws PartInitException {
		super.init(site);
		site.setSelectionProvider(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets
	 * .Composite)
	 */
	@Override
	public void createPartControl(Composite parent) {
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 1;
		gridLayout.marginHeight = 2;
		gridLayout.marginWidth = 2;

		parent.setLayout(gridLayout);

		Composite composite = new Composite(parent, SWT.NONE);
		GridData gridCompositeData = new GridData();
		gridCompositeData.verticalAlignment = GridData.BEGINNING;
		gridCompositeData.horizontalAlignment = GridData.FILL;
		gridCompositeData.grabExcessHorizontalSpace = true;

		composite.setLayoutData(gridCompositeData);

		GridLayout gridCompositeGroupLayout = new GridLayout();
		gridCompositeGroupLayout.numColumns = 3;
		composite.setLayout(gridCompositeGroupLayout);

		Label searchLabel = new Label(composite, SWT.NONE);
		searchLabel.setText("Filter By:"); //$NON-NLS-1$

		searchChoice = SWTUtils.createCombo(composite, new String[] {
				"Order ID", "Order Status", "Customer", "Order Date", "Sales",
				"Shipping Date", "Shipping Address", "Shipping City",
				"Shipping State", "Shipping Country" }, 1);
		searchChoice.select(0);

		searchText = new Text(composite, SWT.BORDER);
		GridData txtGridData = new GridData(GridData.FILL_HORIZONTAL);
		txtGridData.horizontalAlignment = SWT.FILL;
		txtGridData.grabExcessHorizontalSpace = true;
		searchText.setLayoutData(txtGridData);
		searchText.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent event) {
				Text text = (Text) event.widget;
				viewerFilter.setText(text.getText());
				viewer.refresh();
			}
		});

		createTableViewer(parent);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
	 */
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

	public void refreshOrdersView() {

		UIJob refreshJob = new RefreshJob("Refresh");
		refreshJob.setUser(true);
		refreshJob.schedule();

	}

	public void refreshOrdersView(Map<String, Object> searchCriteria) {

		this.searchCriteria = searchCriteria;
		UIJob refreshJob = new RefreshJob("Refresh");
		refreshJob.setUser(true);
		refreshJob.schedule();

	}

	public void createTableViewer(Composite parent) {

		/*
		 * Create table
		 */
		GridData gridData = new GridData();
		gridData.horizontalSpan = 3;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		gridData.verticalAlignment = GridData.FILL;

		table = new Table(parent, SWT.FULL_SELECTION | SWT.BORDER
				| SWT.H_SCROLL | SWT.V_SCROLL);
		table.setLayoutData(gridData);

		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		// id
		TableColumn idColumn = new TableColumn(table, SWT.NONE);
		idColumn.setText("#"); //$NON-NLS-1$
		idColumn.setWidth(60);
		idColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.ORDER_ID,
						sortDirection == SWT.DOWN));
			}
		});

		// order status
		TableColumn statusColumn = new TableColumn(table, SWT.NONE);
		statusColumn.setText("Order Status"); //$NON-NLS-1$
		statusColumn.setWidth(110);
		statusColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.ORDER_STATUS,
						sortDirection == SWT.DOWN));
			}
		});

		// customer name
		TableColumn customerColumn = new TableColumn(table, SWT.NONE);
		customerColumn.setText("Customer"); //$NON-NLS-1$
		customerColumn.setWidth(120);
		customerColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.CUSTOMER,
						sortDirection == SWT.DOWN));
			}
		});

		// order date
		TableColumn dateColumn = new TableColumn(table, SWT.NONE);
		dateColumn.setText("Order Date"); //$NON-NLS-1$
		dateColumn.setWidth(100);
		dateColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.ORDER_DATE,
						sortDirection == SWT.DOWN));
			}
		});

		// gross sales
		TableColumn salesColumn = new TableColumn(table, SWT.NONE);
		salesColumn.setText("Gross Sales"); //$NON-NLS-1$
		salesColumn.setWidth(100);
		salesColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.SALES,
						sortDirection == SWT.DOWN));
			}
		});

		// shipping date
		TableColumn shippingDateColumn = new TableColumn(table, SWT.NONE);
		shippingDateColumn.setText("Shipping Date"); //$NON-NLS-1$
		shippingDateColumn.setWidth(110);
		shippingDateColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.SHIPPING_DATE,
						sortDirection == SWT.DOWN));
			}
		});

		// shipping address
		TableColumn addrColumn = new TableColumn(table, SWT.NONE);
		addrColumn.setText("Shipping Address"); //$NON-NLS-1$
		addrColumn.setWidth(180);
		addrColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.SHIPPING_ADDRESS,
						sortDirection == SWT.DOWN));
			}
		});

		// shipping city
		TableColumn cityColumn = new TableColumn(table, SWT.NONE);
		cityColumn.setText("Shipping City"); //$NON-NLS-1$
		cityColumn.setWidth(110);
		cityColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.SHIPPING_CITY,
						sortDirection == SWT.DOWN));
			}
		});

		// shipping state
		TableColumn stateColumn = new TableColumn(table, SWT.NONE);
		stateColumn.setText("Shipping State"); //$NON-NLS-1$
		stateColumn.setWidth(100);
		stateColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.SHIPPING_STATE,
						sortDirection == SWT.DOWN));
			}
		});

		// shipping country
		TableColumn countryColumn = new TableColumn(table, SWT.NONE);
		countryColumn.setText("Country"); //$NON-NLS-1$
		countryColumn.setWidth(100);
		countryColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				viewer.setSorter(new OrderSorter(
						OrdersTableViewerLabelProvider.SHIPPING_COUNTRY,
						sortDirection == SWT.DOWN));
			}
		});

		/*
		 * Create viewer
		 */
		viewer = new TableViewer(table);

		viewer.setUseHashlookup(true);
		viewer.addFilter(viewerFilter);

		viewer.setLabelProvider(labelProvider);
		viewer.setContentProvider(new OrdersTableViewerContentProvider());

		// create popup menu
		registerPopupMenuAction();

		// tableViewer.setComparator(new
		// TableViewerComparator(this.tableViewer));

		refreshOrdersView();
	}

	private void registerPopupMenuAction() {
		MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
		menuMgr.setRemoveAllWhenShown(true);
		// menuMgr.addMenuListener(new IMenuListener() {
		// public void menuAboutToShow(IMenuManager manager) {
		// manager.add(new Action("View Order Items") {
		// @Override
		// public void run() {
		// }
		//
		// @Override
		// public boolean isEnabled() {
		// return true;
		// }
		//
		// });
		// }
		// });
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	/**
	 * 
	 * @param site
	 * @return
	 */
	public static OrdersListView getOrdersListViewPart(IViewSite site) {
		IViewPart view = site.getPage().findView(OrdersListView.ID_VIEW);
		if (view instanceof OrdersListView) {
			return ((OrdersListView) view);
		}
		return null;
	}

	/**
	 * hook up the selection change listener
	 * 
	 * @param listener
	 */
	public void addSelectionChangedListener(ISelectionChangedListener listener) {
		this.viewer.addSelectionChangedListener(listener);
	}

	private final class OrderFilter extends ViewerFilter {
		private String text;

		public void setText(final String s) {
			this.text = s;
		}

		@Override
		public boolean select(final Viewer viewer, final Object parentElement,
				final Object element) {
			boolean result = true;
			if (text != null && text.length() > 0) {
				String txt = labelProvider.getColumnText(element, searchChoice
						.getSelectionIndex());
				result = txt.toLowerCase().indexOf(text.toLowerCase()) != -1;
			}
			return result;
		}

		@Override
		public boolean isFilterProperty(final Object element, final String prop) {
			return true;
		}
	}

	@Override
	public ISelection getSelection() {
		if (viewer != null) {
			return viewer.getSelection();
		}
		return null;
	}

	@Override
	public void removeSelectionChangedListener(
			ISelectionChangedListener listener) {
		if (viewer != null) {
			viewer.removeSelectionChangedListener(listener);
		}
	}

	@Override
	public void setSelection(ISelection selection) {
		if (viewer != null) {
			viewer.setSelection(selection);
		}
	}

	private class RefreshJob extends UIJob {

		public RefreshJob(String name) {
			super(name);
		}

		@Override
		public IStatus runInUIThread(IProgressMonitor monitor) {
			monitor.beginTask("Refreshing Orders List...",
					IProgressMonitor.UNKNOWN);
			try {
				if (searchCriteria != null && searchCriteria.size() > 0) {
					orders = new OrderDAOImpl().searchOrders(searchCriteria)
							.toArray(new PurchaseOrder[0]);
				} else {
					orders = new OrderDAOImpl().getAllOrder().toArray(
							new PurchaseOrder[0]);
				}

			} catch (DataAccessException e) {
				Alerts.getInstance().detailError("Data Access Error",
						e.getLocalizedMessage(), e);
				return Status.CANCEL_STATUS;
			}

			if (orders != null) {
				viewer.setInput(orders);
			}

			monitor.done();

			return Status.OK_STATUS;
		}
	}

	private class OrderSorter extends ViewerSorter {
		private int columnIndex;
		private final boolean ascending;

		public OrderSorter(int criteria, boolean ascending) {
			super();
			this.columnIndex = criteria;
			this.ascending = ascending;
		}

		@SuppressWarnings("unchecked")
		@Override
		public int compare(Viewer viewer, Object e1, Object e2) {
			int result = 0;
			if (e1 instanceof PurchaseOrder && e2 instanceof PurchaseOrder) {
				result = getComparator().compare(
						labelProvider.getColumnText(e1, columnIndex),
						labelProvider.getColumnText(e2, columnIndex));
			}

			if (!ascending) {
				result = result * -1;
			}
			return result;
		}
	}
}
